/**
 * IndexedDB 工具类，用于管理数据库操作
 */
export default class IndexedDB {
  constructor(dbName, storeName) {
    this.dbName = dbName // 数据库名称
    this.storeName = storeName // 数据表名称
    this.db = null // 数据库实例
  }

  /**
   * 初始化数据库
   */
  async initDB() {
    return new Promise((resolve, reject) => {
      const request = indexedDB.open(this.dbName, 1)

      request.onupgradeneeded = (event) => {
        this.db = event.target.result
        if (!this.db.objectStoreNames.contains(this.storeName)) {
          this.db.createObjectStore(this.storeName, { keyPath: 'id', autoIncrement: true })
        }
      }

      request.onsuccess = (event) => {
        this.db = event.target.result
        resolve('数据库初始化成功')
      }

      request.onerror = (event) => {
        console.error('数据库初始化失败:', event)
        reject('数据库初始化失败')
      }
    })
  }

  /**
   * 关闭数据库连接
   */
  closeDB() {
    if (this.db) {
      this.db.close()
      this.db = null
    }
  }

  /**
   * 添加数据到对象存储
   * @param {Object} data - 数据对象
   */
  async addData(data) {
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(this.storeName, 'readwrite')
      const store = transaction.objectStore(this.storeName)
      const request = store.add(data)

      request.onsuccess = () => resolve('数据添加成功')
      request.onerror = (event) => reject('数据添加失败:', event)
    })
  }

  /**
   * 获取所有数据
   */
  async getAllData() {
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(this.storeName, 'readonly')
      const store = transaction.objectStore(this.storeName)
      const request = store.getAll()

      request.onsuccess = (event) => resolve(event.target.result)
      request.onerror = (event) => reject('获取数据失败:', event)
    })
  }

  /**
   * 根据 ID 删除数据
   * @param {Number} id - 数据 ID
   */
  async deleteData(id) {
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(this.storeName, 'readwrite')
      const store = transaction.objectStore(this.storeName)
      const request = store.delete(id)

      request.onsuccess = () => resolve('数据删除成功')
      request.onerror = (event) => reject('数据删除失败:', event)
    })
  }

  /**
   * 清空对象存储中的所有数据
   */
  async clearData() {
    return new Promise((resolve, reject) => {
      const transaction = this.db.transaction(this.storeName, 'readwrite')
      const store = transaction.objectStore(this.storeName)
      const request = store.clear()

      request.onsuccess = () => resolve('数据已清空')
      request.onerror = (event) => reject('清空数据失败:', event)
    })
  }

  /**
   * 删除整个数据库
   */
  async deleteDatabase() {
    return new Promise((resolve, reject) => {
      const request = indexedDB.deleteDatabase(this.dbName)

      request.onsuccess = () => resolve('数据库已删除')
      request.onerror = (event) => reject('删除数据库失败:', event)
      request.onblocked = () => reject('删除数据库被阻止，请关闭其他页面的连接')
    })
  }
}
